package cn.calm.database.action;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.osgi.interceptor.ServiceAware;

import cn.calm.commons.action.CurdAction;
import cn.calm.database.entity.TableInfo;
import cn.calm.database.service.IDatabaseService;

@SuppressWarnings({"rawtypes","unchecked"})
public class DatabaseAction<T extends TableInfo,S extends IDatabaseService<T>> extends
CurdAction<T,S> implements ServiceAware<IDatabaseService>{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger
			.getLogger(DatabaseAction.class);
	private IDatabaseService<T> databaseService;
	private String sql;
	private List<List<String>> resultData;
	private List<String> resultHead;
	private SqlExceptionCodeMessage codeMessage;

	public String executSql() {
		log.debug("executSql start");
		try {
			List<List<String>> result = databaseService.executSql(sql);
			if (result.size() > 0) {
				resultHead = result.get(0);
				resultData = result.subList(1, result.size());
			}
		} catch (SQLException e) {
			// 1050
			// 42S01
			// com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table
			// 't_parameter123' already exists
			codeMessage.addMessage(this, e);
		}
		log.debug("executSql end");
		return "executSql";
	}

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public List<List<String>> getResultData() {
		return resultData;
	}

	public void setResultData(List<List<String>> resultData) {
		this.resultData = resultData;
	}

	public List<String> getResultHead() {
		return resultHead;
	}

	public void setResultHead(List<String> resultHead) {
		this.resultHead = resultHead;
	}

	@Override
	public String getModeName() {
		return "database";
	}

	public SqlExceptionCodeMessage getCodeMessage() {
		return codeMessage;
	}

	public void setCodeMessage(SqlExceptionCodeMessage codeMessage) {
		this.codeMessage = codeMessage;
	}
	
	@Override
	public Map<String, List<String>> getFieldErrors() {
		return super.getFieldErrors();
	}

	@Override
	public Collection<String> getActionErrors() {
		return super.getActionErrors();
	}

	@Override
	public void setServices(List<IDatabaseService> services) {
		databaseService=(IDatabaseService<T>) services.get(0);
		service=(S) databaseService;
	}

	@Override
	public Class<T> getEntityClass() {
		return (Class<T>) TableInfo.class;
	}
	
}
